package com.zhiche.wms.app.controller.inbound;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.zhiche.wms.app.vo.AppQueryVo;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.core.supports.enums.InterfaceVisitTypeEnum;
import com.zhiche.wms.domain.model.stock.SkuStore;
import com.zhiche.wms.dto.inbound.InboundDTO;
import com.zhiche.wms.dto.inbound.InboundNoticeDTO;
import com.zhiche.wms.dto.inbound.InboundPutawayDTO;
import com.zhiche.wms.dto.opbaas.paramdto.CommonConditionParamDTO;
import com.zhiche.wms.service.constant.PutAwayType;
import com.zhiche.wms.service.constant.SourceSystem;
import com.zhiche.wms.service.inbound.IInboundNoticeLineService;
import com.zhiche.wms.service.inbound.IInboundPutawayHeaderService;
import com.zhiche.wms.service.inbound.IInboundPutawayLineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;


/**
 * 入库
 */
@Api(value = "inboundNoticeLine-API", description = "入库分配接口")
@Controller
@RequestMapping(value = "/inboundNoticeLine")
public class InboundNoticeLineController {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());
    @Autowired
    private IInboundNoticeLineService inboundNoticeLineService;
    @Autowired
    private IInboundPutawayHeaderService iinboundPutawayHeaderService;
    @Autowired
    private IInboundPutawayLineService iInboundPutawayLineService;

    /**
     * 分配入库--模糊匹配
     */
    @PostMapping(value = "/selectByPage")
    @ResponseBody
    @ApiOperation(value = "模糊搜索入库通知", notes = "模糊搜索入库通知", response = InboundNoticeDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "模糊搜索关键字"),
            @ApiImplicitParam(name = "houseId", value = "仓库号"),
            @ApiImplicitParam(name = "size", value = "每页数量"),
            @ApiImplicitParam(name = "current", value = "页数")
    })
    public RestfulResponse<List<InboundNoticeDTO>> selectByPage(AppQueryVo page) {
        LOGGER.info("selectByPage,Params：{}", page.toString());
        RestfulResponse<List<InboundNoticeDTO>> restfulResponse = new RestfulResponse<>(0, "success", null);
        try {
            restfulResponse.setData(inboundNoticeLineService.selectInboundsPage(page.getKey(), page.getHouseId(), page.getSize(), page.getCurrent()).getRecords());
        } catch (BaseException e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage("操作失败，请重试");
        }
        return restfulResponse;
    }

    /**
     * 入库确认-获取详情
     */
    @PostMapping(value = "/selectById")
    @ResponseBody
    @ApiOperation(value = "查询详情", notes = "查询单个入库通知详情", response = InboundNoticeDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "关键id号"),
            @ApiImplicitParam(name = "houseId", value = "仓库号"),
            @ApiImplicitParam(name = "visitType", value = "进入方式（SCAN扫码/CLICK单击）")
    })
    public RestfulResponse<InboundNoticeDTO> selectById(AppQueryVo page) {
        LOGGER.info("selectById,Params：{}", page.toString());
        RestfulResponse<InboundNoticeDTO> restfulResponse = new RestfulResponse<>(0, "success", null);
        try {
            //判断查询的方式
            if (InterfaceVisitTypeEnum.CLICK_TYPE.getCode().equals(page.getVisitType())) {
                //单击单条信息转入
                restfulResponse.setData(inboundNoticeLineService.selectInbound(new Long(page.getKey()), page.getHouseId()));
            } else if (InterfaceVisitTypeEnum.SCAN_TYPE.getCode().equals(page.getVisitType())) {
                //扫码转入
                restfulResponse.setData(inboundNoticeLineService.selectInboundByQrCode(page.getKey(), page.getHouseId()));
            }
        } catch (BaseException e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage("操作失败，请重试");
        }
        return restfulResponse;
    }


    /**
     * 扫码/输入绑定实车位置
     */
    @PostMapping("/bindStoreDetail")
    @ResponseBody
    @ApiOperation(value = "绑定实车停放位置", notes = "入库前/后绑定实车停放位置方便找车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "condition[houseId]", value = "绑定仓库id", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "condition[lotNo1]", value = "车架号", required = true, dataTypeClass = String.class)
    })
    public RestfulResponse<Object> bindStoreDetail(CommonConditionParamDTO dto) {
        LOGGER.info("{}/bindStoreDetail-->param:{}", getClass(), JSONObject.toJSONString(dto));
        RestfulResponse<Object> response = new RestfulResponse<>(0, "操作成功", null);
        SkuStore store = inboundNoticeLineService.updateBindStoreDetail(dto);
        response.setData(store);
        return response;
    }

    /**
     * 入库确认--app
     */
    @PostMapping(value = "/inbound")
    @ResponseBody
    @ApiOperation(value = "分配入库", notes = "将对应id的入库信息进行分配", response = InboundPutawayDTO.class)
    @ApiImplicitParams(@ApiImplicitParam(name = "key", value = "分配入库的id号"))
    public RestfulResponse<InboundPutawayDTO> noticeInBound(AppQueryVo page) {
        LOGGER.info("updateValueNoticeLineInBound,Params：{}", page.toString());
        RestfulResponse<InboundPutawayDTO> restfulResponse = new RestfulResponse<>(0, "success", null);
        try {
            //进行入库分配
            Long putwayLineId = iinboundPutawayHeaderService.updateByNoticeLineId(new Long(page.getKey()), PutAwayType.NOTICE_PUTAWAY,
                    SourceSystem.APP).getInboundPutawayLineList().get(0).getId();
            //查询分配的入库单
            InboundPutawayDTO putwaydto = iInboundPutawayLineService.getPutWaylineById(putwayLineId);
            restfulResponse.setData(putwaydto);
        } catch (BaseException e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage("操作失败，请重试");
        }
        return restfulResponse;
    }

    /**
     * 查询入库通知的分页数据
     */
    @PostMapping("/selectPlanByPage")
    @ResponseBody
    public RestfulResponse<Page<InboundDTO>> selectPlanByPage(AppQueryVo appQueryVo) {
        RestfulResponse<Page<InboundDTO>> restfulResponse = new RestfulResponse<>(0, "success", null);
        try {
            Page<InboundDTO> page = new Page<>();
            HashMap<String, Object> ct = Maps.newHashMap();
            page.setCondition(ct);
            page.getCondition().put("status", appQueryVo.getStatus());
            page.getCondition().put("houseId", appQueryVo.getHouseId());
            page.setCurrent(appQueryVo.getCurrent());
            page.setSize(appQueryVo.getSize());
            Page<InboundDTO> inboundDTOPage = inboundNoticeLineService.selectInboundTask(page);
            restfulResponse.setData(inboundDTOPage);
        } catch (BaseException e) {
            //对自定义异常信息的处理
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            //对controller中的非自定义异常做处理
            LOGGER.error("Controller:\t" + e.toString());
            restfulResponse.setCode(-1);
            restfulResponse.setMessage("操作失败，请重试");
        }
        return restfulResponse;
    }

}